<?php
/**
 * 钉钉登录插件 - 测试连接
 */

header('Content-Type: application/json; charset=utf-8');

// 接收表单数据
$appKey = $_POST['app_key'] ?? '';
$appSecret = $_POST['app_secret'] ?? '';
$corpId = $_POST['corp_id'] ?? '';

// 验证必填项
if (empty($appKey) || empty($appSecret) || empty($corpId)) {
    echo json_encode([
        'success' => false,
        'message' => '请填写 AppKey、AppSecret 和 CorpId'
    ]);
    exit;
}

try {
    // 获取 access_token 测试连接
    $tokenUrl = 'https://oapi.dingtalk.com/gettoken?appkey=' . urlencode($appKey) . '&appsecret=' . urlencode($appSecret);
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $tokenUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpCode !== 200) {
        echo json_encode([
            'success' => false,
            'message' => '连接钉钉服务器失败，HTTP 状态码：' . $httpCode
        ]);
        exit;
    }
    
    $result = json_decode($response, true);
    
    if (isset($result['errcode']) && $result['errcode'] === 0) {
        echo json_encode([
            'success' => true,
            'message' => '钉钉连接测试成功！AppKey 和 AppSecret 配置正确',
            'access_token' => substr($result['access_token'], 0, 20) . '...'
        ]);
    } else {
        $errorMsg = $result['errmsg'] ?? '未知错误';
        echo json_encode([
            'success' => false,
            'message' => '钉钉 API 返回错误：' . $errorMsg
        ]);
    }
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => '测试连接异常：' . $e->getMessage()
    ]);
}
